/** Copyright 2020 Zhejiang Lab and Zhejiang University. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================
*/


import { ROOT_URL } from '../../config'
import axios from 'axios'
import { parseTime, setDialogContent, setIsDialogOpen, shareData, getPrivilege, setIsLoading } from '../utils'

// initial state
const state = {
    errors: "",
    my_datasets: [],
    public_datasets: [],
    is_dialog_open: false,
    dialog_content: "",
    is_loading: false,
}

// getters
const getters = {
}

// actions
const actions = {
    getMyDatasets({ commit, state }) {
        axios.get(`${ROOT_URL}/api/dataset/datasets`, {
        })
            .then((response) => {
                const datasets = response.data;
                for (let d of datasets) {
                    d.created_time = parseTime(d.created_time)
                    d.is_public = d.is_public? "是": "否"
                }
                console.log('get my datasets')
                commit('setMyDatasets', datasets)
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setMyDatasets', [])
                commit('setErrors', errors)
            })
    },
    getPublicDatasets({ commit, state }) {
        axios.get(`${ROOT_URL}/api/dataset/public_datasets`, {
        })
            .then((response) => {
                const datasets = response.data;
                for (let d of datasets) {
                    d.created_time = parseTime(d.created_time)
                }
                console.log('get public datasets')
                commit('setPublicDatasets', datasets)
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setPublicDatasets', [])
                commit('setErrors', errors)
            })
    },
    postDataset({ dispatch, commit, state }, { file_info, file }) {
        console.log("post dataset", file_info, file)
        if (file_info.dataset_name.length == 0) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "数据集名称不得为空")
        }
        else if (file == null) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "模型文件不得为空")
        }
        else {
            commit("setIsLoading", true)
            const formData = new FormData();
            formData.append('file', file);
            formData.append('file_info', JSON.stringify(file_info));
            console.log('formData', formData)
            axios.post(`${ROOT_URL}/api/dataset/datasets`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                }
            })
                .then((response) => {
                    console.log("post ok", response)
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", "创建成功")
                    commit("setIsLoading", false)
                    // dispatch('getDatasets')
                })
                .catch((errors) => {
                    console.log("post error", errors)
                    commit("setErrors", errors)
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", "创建失败")
                    commit("setIsLoading", false)
                })
        }
    },
    updateDataset({ dispatch, commit, state }, { file_info, dataset_id }) {
        console.log("post dataset", file_info)
        if (file_info.dataset_name.length == 0) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "数据集名称不得为空")
        }
        else {
            commit("setIsLoading", true)
            const formData = new FormData();
            file_info['dataset_id']=dataset_id
            formData.append('file_info', JSON.stringify(file_info));
            console.log('formData', formData)
            axios.put(`${ROOT_URL}/api/dataset/datasets`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                }
            })
                .then((response) => {
                    console.log("put ok", response)
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", "更新成功")
                    commit("setIsLoading", false)
                    // dispatch('getDatasets')
                })
                .catch((errors) => {
                    console.log("put error", errors)
                    commit('setErrors', errors)
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", "更新失败")
                    commit("setIsLoading", false)
                })
        }
    },
    deleteDatasets({ dispatch, commit, state }, dataset_ids) {
        console.log('selected', dataset_ids)
        axios.delete(`${ROOT_URL}/api/dataset/datasets`, {
            params: {
                dataset_ids: dataset_ids
            }
        })
            .then((response) => {
                console.log('delete success')
                commit("setIsDialogOpen", true)
                commit("setDialogContent", "删除成功")
                dispatch('getMyDatasets')
            })
            .catch((errors) => {
                console.log('delete failure')
                commit("setIsDialogOpen", true)
                commit("setDialogContent", "删除失败")
                commit('setErrors', errors)
                dispatch('getMyDatasets')
            })
    },
    shareData, getPrivilege
}

const mutations = {
    setErrors(state, errors) {
        state.errors = errors
    },
    setUploadOptions(state, options) {
        state.options = options
    },
    setMyDatasets(state, datasets) {
        state.my_datasets = datasets
    },
    setPublicDatasets(state, datasets) {
        state.public_datasets = datasets
    },
    setIsLoading,
    setDialogContent, setIsDialogOpen
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}